<script id="draw-shader-vs" type="x-shader/x-vertex">
precision mediump float;

attribute vec3 inPos;
attribute vec3 inNV;
attribute vec3 inCol;

varying vec3 vertPos;
varying vec3 vertNV;
varying vec3 vertCol;
varying vec4 vPosPrj;

uniform mat4 u_projectionMat44;
uniform mat4 u_modelViewMat44;

void main()
{
    vertNV      = mat3( u_modelViewMat44 ) * normalize( inNV );
    vertCol     = inCol;
    vec4 pos    = u_modelViewMat44 * vec4( inPos, 1.0 );
    vertPos     = pos.xyz / pos.w;
    vPosPrj     = u_projectionMat44 * pos;
    gl_Position = vPosPrj;
}
</script>

<script id="depth-shader-fs" type="x-shader/x-fragment">
precision mediump float;

varying vec3 vertPos;
varying vec3 vertNV;
varying vec3 vertCol;
varying vec4 vPosPrj;

uniform vec2 u_depthRange;

vec3 PackDepth( in float depth )
{
    float depthVal = depth * (256.0*256.0*256.0 - 1.0) / (256.0*256.0*256.0);
    vec4 encode = fract( depthVal * vec4(1.0, 256.0, 256.0*256.0, 256.0*256.0*256.0) );
    return encode.xyz - encode.yzw / 256.0 + 1.0/512.0;
}

void main()
{
    float ndc_depth = vPosPrj.z / vPosPrj.w;
    float nearZ     = u_depthRange.x;
    float farZ      = u_depthRange.y;
    //float depth     = (((farZ-nearZ) * ndc_depth) + nearZ + farZ) / 2.0;
    float depth     = ndc_depth * 0.5 + 0.5;
    gl_FragColor    = vec4( PackDepth( depth ).xyz, 1.0 );
} 
</script>

<script id="normal-shader-fs" type="x-shader/x-fragment">
precision mediump float;

varying vec3 vertPos;
varying vec3 vertNV;
varying vec3 vertCol;
varying vec4 vPosPrj;

void main()
{
    gl_FragColor = vec4( normalize( vertNV ).xyz * 0.5 + 0.5, 1.0 );
} 
</script>

<script id="ssao-shader-vs" type="x-shader/x-vertex">
precision mediump float;

attribute vec2 inPos;
varying   vec2 vPos;

uniform vec2  u_depthRange;
uniform float u_tanFOV_2;
uniform vec2  u_viewportsize;

void main()
{
    float aspect = u_viewportsize.x / u_viewportsize.y;
    float farLen = u_tanFOV_2 * u_depthRange.y;
    vPos         = inPos;
    gl_Position  = vec4( inPos, 0.0, 1.0 );
}
</script>

<script id="ssao-shader-fs" type="x-shader/x-fragment">
precision mediump float;

varying vec2 vPos;

uniform sampler2D u_depthSampler;
uniform sampler2D u_normalSampler;
uniform sampler2D u_ssaoKernelSampler;
uniform sampler2D u_ssaoNoiseSampler;
uniform float     u_radius;
uniform vec2      u_viewportsize;
uniform vec2      u_depthRange;
uniform float     u_tanFOV_2;
uniform mat4      u_projectionMat44;
uniform mat4      u_InverseProjectionMat44;

float UnpackDepth( in vec3 pack )
{
    float depth = dot( pack, 1.0 / vec3(1.0, 256.0, 256.0*256.0) );
    return depth * (256.0*256.0*256.0) / (256.0*256.0*256.0 - 1.0);
}

float DecodeDepth( in vec2 texC )
{
    vec3  depthVal = texture2D( u_depthSampler, texC.st ).xyz;  
    float depth    = UnpackDepth( depthVal.rgb );
    depth         += step(depth, 0.0); //! depth pack contains 0.0 for background!
    return depth;
}

vec3 DecodeNV( in vec2 texC )
{
    vec3 normalVal = texture2D( u_normalSampler, texC.st ).xyz;  
    return normalVal * 2.0 - 1.0;
}

vec3 DecodePosDepth( in vec2 texC, in float depth )
{
    vec4 viewPos  = u_InverseProjectionMat44 * vec4(vec3(texC.st, depth) * 2.0 - 1.0, 1.0);
    viewPos.xyz  /= viewPos.w;
    return vec3(viewPos.xyz);
}

vec4 SSAO(in vec2 texC)
{
    float occlusion       = 0.0;
    float fragDepth       = DecodeDepth( texC );
    float alpha           = 0.0;
    if (fragDepth < 1.0)
    {
        vec3  fragPos         = DecodePosDepth(texC, fragDepth); 
        float radius          = u_radius;
        vec3  fragNV          = DecodeNV(texC.st);
        vec2  noiseScale      = u_viewportsize / float(4.0);
        vec3  randomVec       = texture2D(u_ssaoNoiseSampler, texC.st * noiseScale).xyz * 2.0- 1.0;
        vec3  tangent         = normalize(randomVec - fragNV * dot( randomVec, fragNV ));
        mat3  TBN             = mat3(tangent, cross( fragNV, tangent ), fragNV);
        float kernelPtCount   = 0.0;
        for( int inx = 0; inx < 32; ++ inx )
        {
            vec4  kernelVec       = texture2D(u_ssaoKernelSampler, vec2(float(inx)/32.0, 0.0) );
            vec3  sampleRel       = TBN * ((kernelVec.xyz * 2.0 - 1.0) * kernelVec.w);
            sampleRel             = fragPos.xyz + sampleRel * radius;
            vec4  sampleTexC      = u_projectionMat44 * vec4(sampleRel, 1.0);             // view to clip space
            sampleTexC.xyz        = 0.5 + 0.5 * sampleTexC.xyz / sampleTexC.w; // clip space -> NDC [-1.0, 1.0] -> [0.0, 1.0]
            float sampleDepth     = sampleTexC.z;
            vec2  rangeTest       = step( vec2( 0.0, 0.0 ), sampleTexC.xy ) * step( sampleTexC.xy, vec2( 1.0, 1.0 ) );
            float w               = rangeTest.x * rangeTest.y;
            kernelPtCount        += w;
            float testDepth       = DecodeDepth(sampleTexC.xy);
            float sampleDelta     = testDepth - sampleDepth;
            occlusion            += w * step(-0.000005, sampleDelta);
        }
        occlusion = occlusion / kernelPtCount;
        alpha     = 1.0;
    }
    return vec4(vec3(occlusion), alpha);
}

void main()
{
    vec2  uvVarying = vPos.st * 0.5 + 0.5;
    gl_FragColor    = SSAO(uvVarying.st);
}
</script>

<script id="blur-shader-vs" type="x-shader/x-vertex">
precision mediump float;

attribute vec2 inPos;

varying   vec2 pos;

void main()
{
    pos = inPos;
    gl_Position = vec4( inPos, 0.0, 1.0 );
}
</script>

<script id="blur-shader-fs" type="x-shader/x-fragment">
precision mediump float;

varying vec2 pos;

uniform sampler2D u_ssaoSampler;
uniform vec2      u_viewportsize;
uniform float     u_blur;

float SSAO44( in sampler2D ssaoSampler, in vec2 texC )
{
    vec2 texOffs = 1.0 / u_viewportsize;
    float ssao = texture2D( ssaoSampler, texC.st ).x;  
    for ( int inxX = -1; inxX < 3; ++ inxX )
    {
        for ( int inxY = -1; inxY < 3; ++ inxY )
            ssao += texture2D( ssaoSampler, texC.st + texOffs * vec2( int(inxX), int(inxY) ) ).x;
    }
    return ssao / 16.0;
}

void main()
{
    vec2 texC    = pos.st * 0.5 + 0.5;
    vec4 texCol  = texture2D( u_ssaoSampler, texC );
    float ssao   = SSAO44( u_ssaoSampler, texC );
    ssao         = mix( texCol.r, ssao, u_blur );
    gl_FragColor = vec4( mix( vec3(0.9, 0.7, 0.9), vec3( ssao ), texCol.a ), 1.0 );
    //gl_FragColor = vec4( texCol.xyz, 1.0 );
}
</script>

<body>

<style>
html,body { margin: 0; overflow: hidden; }
#gui { position : absolute; top : 0; left : 0; font-size : large; }
#ref-link { position : absolute; bottom : 0; left : 0; font-size : large; }  
</style>

<div><form id="gui" name="inputs">
<table>
    <tr> <td> <font color=#40f040>radius</font> </td> 
            <td> <input type="range" id="radius" min="0" max="100" value="50"/></td></tr>
    <tr> <td> <font color=#40f040>blur</font> </td> 
            <td> <input type="checkbox" id="blur" value="1" /></td></tr>
</table>
</form></div>

<canvas id="ssao-canvas" style="border: none;"></canvas>

<script type="text/javascript">

(function loadscene() {

var sliderScale = 100.0
var gl;
var canvas;
var bufCube = {};
var bufTorus = {}
var bufSSAOQuad = {};
var bufQuad = {};
var vp_size;
var progDepth;
var progNormal; 
var progSSAO;
var progBlur;
var ssaoTextures;
var framebuffers = [];
var texUnitDepth = 1;
var texUnitNormal = 2;
var texUnitBlurX = 3;
var texUnitSSAOKErnel = 4;
var texUnitSSAONoise = 5;
var camera;

function render(deltaMS) {

    var shininess = 10.0;
    var radius = 0.1 + 0.9 * document.getElementById( "radius" ).value / sliderScale;
    var blur = document.getElementById( "blur" ).checked;
    var blurVal = blur ? 1 : 0 
    
    // setup view projection and model
    vp_size = [canvas.width, canvas.height];
    camera.Update( vp_size );
    var prjMat = camera.Perspective();
    var invPrjMat = InverseMat44( prjMat );
    var viewMat = camera.Orbit();
    var modelMat = IdentM44();
    modelMat = camera.AutoModelMatrix();

    gl.enable( gl.DEPTH_TEST );
    gl.clearColor( 0.0, 0.0, 0.0, 1.0 );

    // 0: write depth to frame buffer
    // 1: write normal vector to frame buffer
    for ( var fbI = 0; fbI < 2; ++ fbI )
    {
        var passProg = fbI == 0 ? progDepth : progNormal;

        // set up framebuffer for
        framebuffers[fbI].Bind( true );
        
        // set up depth draw shader
        ShProg.Use( passProg );
        ShProg.SetM44( passProg, "u_projectionMat44", prjMat );
        ShProg.SetM44( passProg, "u_modelViewMat44", Multiply(viewMat, modelMat) );
        ShProg.SetF2( passProg,  "u_depthRange", [ camera.near, camera.far ] );
        
        // draw scene
        for( var objI = 0; objI < 2; ++ objI )
            VertexBuffer.Draw( objI == 0 ? bufCube : bufTorus );
    }

    // set blur-X framebuffer and bind frambuffer texture
    framebuffers[2].Bind( true );
    framebuffers[0].BindTexture( texUnitDepth );
    framebuffers[1].BindTexture( texUnitNormal );
   
    // set up SSAO shader
    var tanFOV_2 = Math.tan( Math.PI * camera.fov_y / 360 );
    ShProg.Use( progSSAO );
    ShProg.SetI1( progSSAO, "u_depthSampler", texUnitDepth );
    ShProg.SetI1( progSSAO, "u_normalSampler", texUnitNormal );
    ShProg.SetI1( progSSAO, "u_ssaoKernelSampler", ssaoTextures.kernelTexUnit );
    ShProg.SetI1( progSSAO, "u_ssaoNoiseSampler", ssaoTextures.noiseTexUnit );
    ShProg.SetF1( progSSAO, "u_radius", radius );
    ShProg.SetF2( progSSAO, "u_viewportsize", [ framebuffers[0].width, framebuffers[0].height ] );
    ShProg.SetF2( progSSAO, "u_depthRange", [ Camera.near, Camera.far ] );
    ShProg.SetF1( progSSAO, "u_tanFOV_2", tanFOV_2 );
    ShProg.SetM44( progSSAO, "u_projectionMat44", prjMat );
    ShProg.SetM44( progSSAO, "u_InverseProjectionMat44", invPrjMat );
        
    // draw full screen space
    VertexBuffer.Draw( bufSSAOQuad );

    // reset framebuffer and bind frambuffer texture
    framebuffers[0].Release( true );
    gl.viewport( 0, 0, canvas.width, canvas.height );
    framebuffers[2].BindTexture( texUnitBlurX );

    // set up blur process shader
    ShProg.Use( progBlur );
    ShProg.SetI1( progBlur, "u_ssaoSampler", texUnitBlurX )
    ShProg.SetF2( progBlur, "u_viewportsize", [ framebuffers[1].width, framebuffers[1].height ] );
    ShProg.SetF1( progBlur, "u_blur", blurVal );
    
    // draw full screen space
    VertexBuffer.Draw( bufQuad );

    requestAnimationFrame(render);
}    

function initScene() {

    document.getElementById( "blur" ).checked = true;
    canvas = document.getElementById( "ssao-canvas");
    vp_size = [canvas.width, canvas.height];
    gl = canvas.getContext( "experimental-webgl" );
    if ( !gl )
      return;

    progDepth = ShProg.Create( 
      [ { source : "draw-shader-vs", stage : gl.VERTEX_SHADER },
        { source : "depth-shader-fs", stage : gl.FRAGMENT_SHADER }
      ] );
    progDepth.inPos = ShProg.AttrI( progDepth, "inPos" );
    progDepth.inNV  = ShProg.AttrI( progDepth, "inNV" );
    progDepth.inCol = ShProg.AttrI( progDepth, "inCol" );
    if ( progDepth.progObj == 0 )
        return;

    progNormal = ShProg.Create( 
      [ { source : "draw-shader-vs", stage : gl.VERTEX_SHADER },
        { source : "normal-shader-fs", stage : gl.FRAGMENT_SHADER }
      ] );
    progNormal.inPos = ShProg.AttrI( progNormal, "inPos" );
    progNormal.inNV  = ShProg.AttrI( progNormal, "inNV" );
    progNormal.inCol = ShProg.AttrI( progNormal, "inCol" );
    if ( progNormal.progObj == 0 )
        return;

    progSSAO = ShProg.Create( 
      [ { source : "ssao-shader-vs", stage : gl.VERTEX_SHADER },
        { source : "ssao-shader-fs", stage : gl.FRAGMENT_SHADER }
      ] );
    progSSAO.inPos = ShProg.AttrI( progSSAO, "inPos" );
    if ( progSSAO.progObj == 0 )
        return;

    progBlur = ShProg.Create( 
      [ { source : "blur-shader-vs", stage : gl.VERTEX_SHADER },
        { source : "blur-shader-fs", stage : gl.FRAGMENT_SHADER }
      ] );
    progBlur.inPos = ShProg.AttrI( progBlur, "inPos" );
    if ( progBlur.progObj == 0 )
        return; 

    var cubePos = [
        -1.0, -1.0,  1.0,  1.0, -1.0,  1.0,  1.0,  1.0,  1.0, -1.0,  1.0,  1.0,
        -1.0, -1.0, -1.0,  1.0, -1.0, -1.0,  1.0,  1.0, -1.0, -1.0,  1.0, -1.0 ];
    var cubeCol = [ 1.0, 0.0, 0.0, 1.0, 0.5, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 ];
    var cubeHlpInx = [ 0, 1, 2, 3, 1, 5, 6, 2, 5, 4, 7, 6, 4, 0, 3, 7, 3, 2, 6, 7, 1, 0, 4, 5 ]; 
    var cubePosData = [];
    var cubeLen = 0.9;
    for ( var i = 0; i < cubeHlpInx.length; ++ i ) {
        cubePosData.push( cubePos[cubeHlpInx[i]*3]*cubeLen, cubePos[cubeHlpInx[i]*3+1]*cubeLen, cubePos[cubeHlpInx[i]*3+2]*cubeLen );
    }
    var cubeNVData = [];
    for ( var i1 = 0; i1 < cubeHlpInx.length; i1 += 4 ) {
        var nv = [0, 0, 0];
        for ( i2 = 0; i2 < 4; ++ i2 ) {
            var i = i1 + i2;
            nv[0] += cubePosData[i*3]; nv[1] += cubePosData[i*3+1]; nv[2] += cubePosData[i*3+2];
        }
        for ( i2 = 0; i2 < 4; ++ i2 )
          cubeNVData.push( nv[0], nv[1], nv[2] );
    }
    var cubeColData = [];
    for ( var is = 0; is < 6; ++ is ) {
        for ( var ip = 0; ip < 4; ++ ip ) {
           cubeColData.push( cubeCol[is*3], cubeCol[is*3+1], cubeCol[is*3+2] ); 
        }
    }
    var inxData = [];
    for ( var i = 0; i < cubeHlpInx.length; i += 4 ) {
        inxData.push( i, i+1, i+2, i, i+2, i+3 );
    }
    bufCube = VertexBuffer.Create(
        [ { data : cubePosData, attrSize : 3, attrLoc : progDepth.inPos },
          { data : cubeNVData,  attrSize : 3, attrLoc : progDepth.inNV },
          { data : cubeColData, attrSize : 3, attrLoc : progDepth.inCol } ],
          inxData
      );

    // create torus
    var circum_size = 32, tube_size = 32;
    var rad_circum = 1.3;
    var rad_tube = 0.4;
    var torus_pts = [];
    var torus_nv = [];
    var torus_col = [];
    var torus_inx = [];
    var col = [1, 0.5, 0.0];
    for ( var i_c = 0; i_c < circum_size; ++ i_c ) {
        var center = [
            Math.cos(2 * Math.PI * i_c / circum_size),
            Math.sin(2 * Math.PI * i_c / circum_size) ]
        for ( var i_t = 0; i_t < tube_size; ++ i_t ) {
            var tubeX = Math.cos(2 * Math.PI * i_t / tube_size)
            var tubeY = Math.sin(2 * Math.PI * i_t / tube_size)
            var pt = [
                center[0] * ( rad_circum + tubeX * rad_tube ),
                center[1] * ( rad_circum + tubeX * rad_tube ),
                tubeY * rad_tube ]
            var nv = [ pt[0] - center[0] * rad_tube, pt[1] - center[1] * rad_tube, tubeY * rad_tube ]
            torus_pts.push( pt[0], pt[1], pt[2] );
            torus_nv.push( nv[0], nv[1], nv[2] );
            torus_col.push( col[0], col[1], col[2] );
            var i_cn = (i_c+1) % circum_size
            var i_tn = (i_t+1) % tube_size
            var i_c0 = i_c * tube_size; 
            var i_c1 = i_cn * tube_size; 
            torus_inx.push( i_c0+i_t, i_c0+i_tn, i_c1+i_t, i_c0+i_tn, i_c1+i_t, i_c1+i_tn )
        }
    }
    bufTorus = VertexBuffer.Create(
        [ { data : torus_pts, attrSize : 3, attrLoc : progDepth.inPos },
          { data : torus_nv,  attrSize : 3, attrLoc : progDepth.inNV },
          { data : torus_col, attrSize : 3, attrLoc : progDepth.inCol } ],
          torus_inx
      );

    bufSSAOQuad = VertexBuffer.Create( 
        [ { data : [ -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0 ], attrSize : 2, attrLoc : progSSAO.inPos } ],
        [ 0, 1, 2, 0, 2, 3 ]
    );

    bufQuad = VertexBuffer.Create( 
        [ { data : [ -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0 ], attrSize : 2, attrLoc : progBlur.inPos } ],
        [ 0, 1, 2, 0, 2, 3 ]
    );

    ssaoTextures = generateSSAOTextures( 32, 4, texUnitSSAOKErnel, texUnitSSAONoise );   

    camera = new Camera( [0, 2.5, 0.0], [0, 0, 0], [0, 0, 1], 90, vp_size, 0.5, 100 );

    window.onresize = resize;
    resize();
    requestAnimationFrame(render);
}

function resize() {
    //vp_size = [gl.drawingBufferWidth, gl.drawingBufferHeight];
    vp_size = [window.innerWidth, window.innerHeight]
    //vp_size = [256, 256]
    canvas.width = vp_size[0];
    canvas.height = vp_size[1];

    var fbsize = Math.max(vp_size[0], vp_size[1]);
    fbsize = 1 << 31 - Math.clz32(fbsize); // nearest power of 2

    var fb_rect = [fbsize, fbsize];
    framebuffers = [ FrameBuffer.Create( fb_rect ), FrameBuffer.Create( fb_rect ), FrameBuffer.Create( fb_rect ) ]; 
}


vec4_add = function( a, b ) { return [ a[0]+b[0], a[1]+b[1], a[2]+b[2], a[3]+b[3] ]; }
vec4_sub = function( a, b ) { return [ a[0]-b[0], a[1]-b[1], a[2]-b[2], a[3]-b[3] ]; }
vec4_mul = function( a, b ) { return [ a[0]*b[0], a[1]*b[1], a[2]*b[2], a[3]*b[3] ]; }
vec4_scale = function( a, s ) { return [ a[0]*s, a[1]*s, a[2]*s, a[3]*s ]; }

function InverseMat44( m ) {

    var Coef00 = m[2*4+2] * m[3*4+3] - m[3*4+2] * m[2*4+3];
    var Coef02 = m[1*4+2] * m[3*4+3] - m[3*4+2] * m[1*4+3];
    var Coef03 = m[1*4+2] * m[2*4+3] - m[2*4+2] * m[1*4+3];    
    var Coef04 = m[2*4+1] * m[3*4+3] - m[3*4+1] * m[2*4+3];
    var Coef06 = m[1*4+1] * m[3*4+3] - m[3*4+1] * m[1*4+3];
    var Coef07 = m[1*4+1] * m[2*4+3] - m[2*4+1] * m[1*4+3];   
    var Coef08 = m[2*4+1] * m[3*4+2] - m[3*4+1] * m[2*4+2];
    var Coef10 = m[1*4+1] * m[3*4+2] - m[3*4+1] * m[1*4+2];
    var Coef11 = m[1*4+1] * m[2*4+2] - m[2*4+1] * m[1*4+2];   
    var Coef12 = m[2*4+0] * m[3*4+3] - m[3*4+0] * m[2*4+3];
    var Coef14 = m[1*4+0] * m[3*4+3] - m[3*4+0] * m[1*4+3];
    var Coef15 = m[1*4+0] * m[2*4+3] - m[2*4+0] * m[1*4+3];   
    var Coef16 = m[2*4+0] * m[3*4+2] - m[3*4+0] * m[2*4+2];
    var Coef18 = m[1*4+0] * m[3*4+2] - m[3*4+0] * m[1*4+2];
    var Coef19 = m[1*4+0] * m[2*4+2] - m[2*4+0] * m[1*4+2];   
    var Coef20 = m[2*4+0] * m[3*4+1] - m[3*4+0] * m[2*4+1];
    var Coef22 = m[1*4+0] * m[3*4+1] - m[3*4+0] * m[1*4+1];
    var Coef23 = m[1*4+0] * m[2*4+1] - m[2*4+0] * m[1*4+1];
      
    var Fac0 = [Coef00, Coef00, Coef02, Coef03];
    var Fac1 = [Coef04, Coef04, Coef06, Coef07];
    var Fac2 = [Coef08, Coef08, Coef10, Coef11];
    var Fac3 = [Coef12, Coef12, Coef14, Coef15];
    var Fac4 = [Coef16, Coef16, Coef18, Coef19];
    var Fac5 = [Coef20, Coef20, Coef22, Coef23];
      
    var Vec0 = [ m[1*4+0], m[0*4+0], m[0*4+0], m[0*4+0] ];
    var Vec1 = [ m[1*4+1], m[0*4+1], m[0*4+1], m[0*4+1] ];
    var Vec2 = [ m[1*4+2], m[0*4+2], m[0*4+2], m[0*4+2] ];
    var Vec3 = [ m[1*4+3], m[0*4+3], m[0*4+3], m[0*4+3] ];
      
    var Inv0 = vec4_add( vec4_sub( vec4_mul(Vec1, Fac0), vec4_mul(Vec2, Fac1) ), vec4_mul( Vec3, Fac2 ) );
    var Inv1 = vec4_add( vec4_sub( vec4_mul(Vec0, Fac0), vec4_mul(Vec2, Fac3) ), vec4_mul( Vec3, Fac4 ) );
    var Inv2 = vec4_add( vec4_sub( vec4_mul(Vec0, Fac1), vec4_mul(Vec1, Fac3) ), vec4_mul( Vec3, Fac5 ) );
    var Inv3 = vec4_add( vec4_sub( vec4_mul(Vec0, Fac2), vec4_mul(Vec1, Fac4) ), vec4_mul( Vec2, Fac5 ) );
      
    var SignA = [+1.0, -1.0, +1.0, -1.0];
    var SignB = [-1.0, +1.0, -1.0, +1.0];
    var Inverse = [ vec4_mul(Inv0, SignA), vec4_mul(Inv1, SignB), vec4_mul(Inv2, SignA), vec4_mul(Inv3, SignB) ];
      
    var Row0 = [Inverse[0][0], Inverse[1][0], Inverse[2][0], Inverse[3][0] ];
      
    var Dot0 = [Row0[0], Row0[1], Row0[2], Row0[3] ];
    Dot0 = vec4_mul( Dot0, [ m[0], m[1], m[2], m[3] ] );
    var Dot1 = (Dot0[0] + Dot0[1]) + (Dot0[2] + Dot0[3]);
      
    var OneOverDeterminant = 1 / Dot1;

    var res = IdentM44();  
    for ( var inx1 = 0; inx1 < 4; inx1 ++ ) {
        for ( var inx2 = 0; inx2 < 4; inx2 ++ )
            res[inx1*4+inx2] = Inverse[inx1][inx2] * OneOverDeterminant;
    }
    return res;
}

function Fract(val) {
    return val - Math.trunc(val);
}
function CalcAng(deltaTime, interval) {
    return Fract(deltaTime / (1000 * interval)) * 2.0 * Math.PI;
}
function CalcMove(deltaTime, interval, range) {
    var pos = Fract(deltaTime / (1000 * interval)) * 2.0
    var pos = pos < 1.0 ? pos : (2.0 - pos)
    return range[0] + (range[1] - range[0]) * pos;
}
function EllipticalPosition(a, b, angRag) {
    var a_b = a * a - b * b
    var ea = (a_b <= 0) ? 0 : Math.sqrt(a_b);
    var eb = (a_b >= 0) ? 0 : Math.sqrt(-a_b);
    return [a * Math.sin(angRag) - ea, b * Math.cos(angRag) - eb, 0];
}

function IdentM44() { return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; }

function RotateAxis(matA, angRad, axis) {
    var aMap = [ [1, 2], [2, 0], [0, 1] ];
    var a0 = aMap[axis][0], a1 = aMap[axis][1]; 
    var sinAng = Math.sin(angRad), cosAng = Math.cos(angRad);
    var matB = matA.slice(0);
    for ( var i = 0; i < 3; ++ i ) {
        matB[a0*4+i] = matA[a0*4+i] * cosAng + matA[a1*4+i] * sinAng;
        matB[a1*4+i] = matA[a0*4+i] * -sinAng + matA[a1*4+i] * cosAng;
    }
    return matB;
}

function Rotate(matA, angRad, axis) {
    var s = Math.sin(angRad), c = Math.cos(angRad);
    var x = axis[0], y = axis[1], z = axis[2]; 
    matB = [
        x*x*(1-c)+c,   x*y*(1-c)-z*s, x*z*(1-c)+y*s, 0,
        y*x*(1-c)+z*s, y*y*(1-c)+c,   y*z*(1-c)-x*s, 0,
        z*x*(1-c)-y*s, z*y*(1-c)+x*s, z*z*(1-c)+c,   0,
        0,             0,             0,             1 ];
    return Multiply(matA, matB);
}    

function Multiply(matA, matB) {
    matC = IdentM44();
    for (var i0=0; i0<4; ++i0 )
        for (var i1=0; i1<4; ++i1 )
            matC[i0*4+i1] = matB[i0*4+0] * matA[0*4+i1] + matB[i0*4+1] * matA[1*4+i1] + matB[i0*4+2] * matA[2*4+i1] + matB[i0*4+3] * matA[3*4+i1]  
    return matC;
}

function Cross(a, b) { return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0], 0.0]; }
function Dot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; }
function Normalize(v) {
    var len = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
    return [v[0] / len, v[1] / len, v[2] / len];
}

Camera = function( pos, target, up, fov_y, vp, near, far ) {
this.Time = function() { return Date.now(); }
this.pos = pos;
this.target = target;
this.up = up;
this.fov_y = fov_y;
this.vp = vp;
this.near = near;
this.far = far;
this.orbit_mat = this.current_orbit_mat = this.model_mat = this.current_model_mat = IdentM44();
this.mouse_drag = this.auto_spin = false;
this.auto_rotate = true;
this.mouse_start = [0, 0];
this.mouse_drag_axis = [0, 0, 0];
this.mouse_drag_angle = 0;
this.mouse_drag_time = 0;
this.drag_start_T = this.rotate_start_T = this.Time();
this.Ortho = function() {
    var fn = this.far + this.near;
    var f_n = this.far - this.near;
    var w = this.vp[0];
    var h = this.vp[1];
    return [
        2/w, 0,   0,       0,
        0,   2/h, 0,       0,
        0,   0,   -2/f_n,  0,
        0,   0,   -fn/f_n, 1 ];
};  
this.Perspective = function() {
    var n = this.near;
    var f = this.far;
    var fn = f + n;
    var f_n = f - n;
    var r = this.vp[0] / this.vp[1];
    var t = 1 / Math.tan( Math.PI * this.fov_y / 360 );
    return [
        t/r, 0, 0,          0,
        0,   t, 0,          0,
        0,   0, -fn/f_n,   -1,
        0,   0, -2*f*n/f_n, 0 ];
}; 
this.LookAt = function() {
    var mz = Normalize( [ this.pos[0]-this.target[0], this.pos[1]-this.target[1], this.pos[2]-this.target[2] ] );
    var mx = Normalize( Cross( this.up, mz ) );
    var my = Normalize( Cross( mz, mx ) );
    var tx = Dot( mx, this.pos );
    var ty = Dot( my, this.pos );
    var tz = Dot( [-mz[0], -mz[1], -mz[2]], this.pos ); 
    return [mx[0], my[0], mz[0], 0, mx[1], my[1], mz[1], 0, mx[2], my[2], mz[2], 0, tx, ty, tz, 1]; 
};
this.Orbit = function() {
    return Multiply(this.LookAt(), this.OrbitMatrix());
}; 
this.OrbitMatrix = function() {
    return (this.mouse_drag || (this.auto_rotate && this.auto_spin)) ? Multiply(this.current_orbit_mat, this.orbit_mat) : this.orbit_mat;
};
this.AutoModelMatrix = function() {
    return this.auto_rotate ? Multiply(this.current_model_mat, this.model_mat) : this.model_mat;
};
this.Update = function(vp_size) {
    if (vp_size)
        this.vp = vp_size;
    var current_T = this.Time();
    this.current_model_mat = IdentM44()
    if (this.mouse_drag) {
        this.current_orbit_mat = Rotate(IdentM44(), this.mouse_drag_angle, this.mouse_drag_axis);
    } else if (this.auto_rotate) {
        if (this.auto_spin ) {
            if (this.mouse_drag_time > 0 ) {
                var angle = this.mouse_drag_angle * (current_T - this.rotate_start_T) / this.mouse_drag_time;
                this.current_orbit_mat = Rotate(IdentM44(), angle, this.mouse_drag_axis);
            }
        } else {
            var auto_angle_x = Fract( (current_T - this.rotate_start_T) / 13000.0 ) * 2.0 * Math.PI;
            var auto_angle_y = Fract( (current_T - this.rotate_start_T) / 17000.0 ) * 2.0 * Math.PI;
            this.current_model_mat = RotateAxis( this.current_model_mat, auto_angle_x, 0 );
            this.current_model_mat = RotateAxis( this.current_model_mat, auto_angle_y, 1 );
        }
    }
};
this.ChangeMotionMode = function(drag, spin, auto ) {
    var new_drag = drag;
    var new_auto = new_drag ? false : auto;
    var new_spin = new_auto ? spin : false;
    change = this.mouse_drag != new_drag || this.auto_rotate != new_auto || this.auto_spin != new_spin; 
    if (!change)
        return;
    if (new_drag && !this.mouse_drag) {
        this.drag_start_T = this.Time();
        this.mouse_drag_angle = 0.0;
        this.mouse_drag_time = 0;
    }
    if (new_auto && !this.auto_rotate)
        this.rotate_start_T = this.Time();
    this.mouse_drag = new_drag; 
    this.auto_rotate = new_auto;  
    this.auto_spin = new_spin;
    this.orbit_mat = Multiply(this.current_orbit_mat, this.orbit_mat);
    this.current_orbit_mat = IdentM44();
    this.model_mat = Multiply(this.current_model_mat, this.model_mat);
    this.current_model_mat = IdentM44();
};
this.OnMouseDown = function( event ) {
    var rect = gl.canvas.getBoundingClientRect();
    if ( event.clientX < rect.left || event.clientX > rect.right ) return;
    if ( event.clientY < rect.top || event.clientY > rect.bottom ) return;
    if (event.button == 0) { // left button
        this.mouse_start = [event.clientX, event.clientY]; 
        this.ChangeMotionMode( true, false, false );
    }
};
this.OnMouseUp = function( event ) {
    if (event.button == 0) { // left button
        this.ChangeMotionMode( false, true, true );
    } else if (event.button == 1) {// middle button
        this.ChangeMotionMode( false, false, !this.auto_rotate );
    }
};
this.OnMouseMove = function( event ) {
    var dx = (event.clientX-this.mouse_start[0]) / this.vp[0];
    var dy = (event.clientY-this.mouse_start[1]) / this.vp[1];
    var len = Math.sqrt(dx*dx + dy*dy);
    if (this.mouse_drag && len > 0) {
        this.mouse_drag_angle = Math.PI*len;
        this.mouse_drag_axis = [dy/len, 0, -dx/len];
        this.mouse_drag_time = this.Time() - this.drag_start_T;
    }
};

this.domElement = document;
var cam = this;
//this.domElement.addEventListener( 'contextmenu', function(e) { event.preventDefault(); }, false );
this.domElement.addEventListener( 'mousedown', function(e) { cam.OnMouseDown(e) }, false );
this.domElement.addEventListener( 'mouseup', function(e) { cam.OnMouseUp(e) }, false );
this.domElement.addEventListener( 'mousemove', function(e) { cam.OnMouseMove(e) }, false );
//this.domElement.addEventListener( 'mousewheel', hid_events.onMouseWheel, false );
//this.domElement.addEventListener( 'DOMMouseScroll', hid_events.onMouseWheel, false ); // firefox
}

var ShProg = {
Create: function (shaderList) {
    var shaderObjs = [];
    for (var i_sh = 0; i_sh < shaderList.length; ++i_sh) {
        var shderObj = this.Compile(shaderList[i_sh].source, shaderList[i_sh].stage);
        if (shderObj) shaderObjs.push(shderObj);
    }
    var prog = {}
    prog.progObj = this.Link(shaderObjs)
    if (prog.progObj) {
        prog.attrInx = {};
        var noOfAttributes = gl.getProgramParameter(prog.progObj, gl.ACTIVE_ATTRIBUTES);
        for (var i_n = 0; i_n < noOfAttributes; ++i_n) {
            var name = gl.getActiveAttrib(prog.progObj, i_n).name;
            prog.attrInx[name] = gl.getAttribLocation(prog.progObj, name);
        }
        prog.uniLoc = {};
        var noOfUniforms = gl.getProgramParameter(prog.progObj, gl.ACTIVE_UNIFORMS);
        for (var i_n = 0; i_n < noOfUniforms; ++i_n) {
            var name = gl.getActiveUniform(prog.progObj, i_n).name;
            prog.uniLoc[name] = gl.getUniformLocation(prog.progObj, name);
        }
    }
    return prog;
},
AttrI: function (prog, name) { return prog.attrInx[name]; },
UniformL: function (prog, name) { return prog.uniLoc[name]; },
Use: function (prog) { gl.useProgram(prog.progObj); },
SetI1: function (prog, name, val) { if (prog.uniLoc[name]) gl.uniform1i(prog.uniLoc[name], val); },
SetF1: function (prog, name, val) { if (prog.uniLoc[name]) gl.uniform1f(prog.uniLoc[name], val); },
SetF2: function (prog, name, arr) { if (prog.uniLoc[name]) gl.uniform2fv(prog.uniLoc[name], arr); },
SetF3: function (prog, name, arr) { if (prog.uniLoc[name]) gl.uniform3fv(prog.uniLoc[name], arr); },
SetF4: function (prog, name, arr) { if (prog.uniLoc[name]) gl.uniform4fv(prog.uniLoc[name], arr); },
SetM33: function (prog, name, mat) { if (prog.uniLoc[name]) gl.uniformMatrix3fv(prog.uniLoc[name], false, mat); },
SetM44: function (prog, name, mat) { if (prog.uniLoc[name]) gl.uniformMatrix4fv(prog.uniLoc[name], false, mat); },
Compile: function (source, shaderStage) {
    var shaderScript = document.getElementById(source);
    if (shaderScript)
        source = shaderScript.text;
    var shaderObj = gl.createShader(shaderStage);
    gl.shaderSource(shaderObj, source);
    gl.compileShader(shaderObj);
    var status = gl.getShaderParameter(shaderObj, gl.COMPILE_STATUS);
    if (!status) alert(gl.getShaderInfoLog(shaderObj));
    return status ? shaderObj : null;
},
Link: function (shaderObjs) {
    var prog = gl.createProgram();
    for (var i_sh = 0; i_sh < shaderObjs.length; ++i_sh)
        gl.attachShader(prog, shaderObjs[i_sh]);
    gl.linkProgram(prog);
    status = gl.getProgramParameter(prog, gl.LINK_STATUS);
    if ( !status ) alert(gl.getProgramInfoLog(prog));
    return status ? prog : null;
} };

function generateSSAOTextures( kernelSize, noiseSize, kernelTexUnit, noiseTexUnit ) {
    var ssaoObject = {}
    
    ssaoObject.kernel = new Uint8Array( kernelSize * 4 );
    for ( var i_k = 0; i_k < kernelSize; ++ i_k ) {
      var x = Math.random() * 2.0 - 1.0;
      var y = Math.random() * 2.0 - 1.0;
      var z = Math.random() * 2.0 - 1.0;
      var len = Math.sqrt( x * x + y * y + z * z );
      x = x / len; y = y / len;  z = z / len;
      var len_xy = Math.sqrt( x * x + y * y );
      z = z * (1 + len_xy) - len_xy;
      var w = i_k / kernelSize;
      w = 0.1 + 0.9 * w * w;
      //w = 0.01 + 0.99 * w; 
      w = 1.0
      ssaoObject.kernel[i_k*4] = (x + 1.0 ) * 0.5 * 255.0;
      ssaoObject.kernel[i_k*4+1] = (y + 1.0 ) * 0.5 * 255.0;
      ssaoObject.kernel[i_k*4+2] = (z + 1.0 ) * 0.5 * 255.0;
      ssaoObject.kernel[i_k*4+3] = w * 255.0;
    }

    ssaoObject.noise = new Uint8Array( noiseSize * noiseSize * 4 );
    for ( var inx1 = 0; inx1 < 2; inx1 ++ )
    {
      for ( var inx2 = 0; inx2 < noiseSize/2; inx2 ++ )
      {
        var iang = 2*inx2+inx1;
        var angle = 2.0 * Math.PI * iang / noiseSize;
        var inx = inx1*noiseSize / 2 + inx2;
        var x = Math.cos(angle);
        var y = Math.sin(angle);
        var z = 0;
        var len = Math.sqrt( x * x + y * y + z * z );
        ssaoObject.noise[inx*4] = ( x / len + 1.0 ) * 0.5 * 255.0;
        ssaoObject.noise[inx*4+1] = ( y / len + 1.0 ) * 0.5 * 255.0;
        ssaoObject.noise[inx*4+2] = ( z / len + 1.0 ) * 0.5 * 255.0;
        ssaoObject.noise[inx*4+3] = 255.0;
    }
  }

    gl.activeTexture( gl.TEXTURE0+kernelTexUnit );
    ssaoObject.kernelTexUnit = kernelTexUnit;
    ssaoObject.kernelTexture = gl.createTexture();
    gl.bindTexture( gl.TEXTURE_2D, ssaoObject.kernelTexture );
    gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, kernelSize, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, ssaoObject.kernel );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );

    gl.activeTexture( gl.TEXTURE0+noiseTexUnit );
    ssaoObject.noiseTexUnit = noiseTexUnit;
    ssaoObject.noiseTexture = gl.createTexture();
    gl.bindTexture( gl.TEXTURE_2D, ssaoObject.noiseTexture );
    gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, noiseSize, noiseSize, 0, gl.RGBA, gl.UNSIGNED_BYTE, ssaoObject.noise );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT );

    gl.activeTexture( gl.TEXTURE0 );
    return ssaoObject;
};

var VertexBuffer = {
Create: function(attribs, indices, type) {
    var buffer = { buf: [], attr: [], inx: gl.createBuffer(), inxLen: indices.length, primitive_type: type ? type : gl.TRIANGLES };
    for (var i=0; i<attribs.length; ++i) {
        buffer.buf.push(gl.createBuffer());
        buffer.attr.push({ size : attribs[i].attrSize, loc : attribs[i].attrLoc, no_of: attribs[i].data.length/attribs[i].attrSize });
        gl.bindBuffer(gl.ARRAY_BUFFER, buffer.buf[i]);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array( attribs[i].data ), gl.STATIC_DRAW);
    }
    gl.bindBuffer(gl.ARRAY_BUFFER, null);
    if ( buffer.inxLen > 0 ) {
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer.inx);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( indices ), gl.STATIC_DRAW);
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
    }
    return buffer;
},
Draw: function(bufObj) {
    for (var i=0; i<bufObj.buf.length; ++i) {
        gl.bindBuffer(gl.ARRAY_BUFFER, bufObj.buf[i]);
        gl.vertexAttribPointer(bufObj.attr[i].loc, bufObj.attr[i].size, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray( bufObj.attr[i].loc);
    }
    if ( bufObj.inxLen > 0 ) {
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bufObj.inx);
        gl.drawElements(bufObj.primitive_type, bufObj.inxLen, gl.UNSIGNED_SHORT, 0);
        gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
    }
    else
        gl.drawArrays(bufObj.primitive_type, 0, bufObj.attr[0].no_of );
    for (var i=0; i<bufObj.buf.length; ++i)
        gl.disableVertexAttribArray(bufObj.attr[i].loc);
    gl.bindBuffer( gl.ARRAY_BUFFER, null );
} };

var FrameBuffer = {};
FrameBuffer.Create = function( vp, texturePlan ) {
    var texPlan = texturePlan ? new Uint8Array( texturePlan ) : null;
    var fb = gl.createFramebuffer();
    fb.width = vp[0];
    fb.height = vp[1];
    gl.bindFramebuffer( gl.FRAMEBUFFER, fb );
    fb.color0_texture = gl.createTexture();
    gl.bindTexture( gl.TEXTURE_2D, fb.color0_texture );
    gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, fb.width, fb.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, texPlan );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
    fb.renderbuffer = gl.createRenderbuffer();
    gl.bindRenderbuffer( gl.RENDERBUFFER, fb.renderbuffer );
    gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, fb.width, fb.height );
    gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, fb.color0_texture, 0 );
    gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, fb.renderbuffer );
    gl.bindTexture( gl.TEXTURE_2D, null );
    gl.bindRenderbuffer( gl.RENDERBUFFER, null );
    gl.bindFramebuffer( gl.FRAMEBUFFER, null );

    fb.Bind = function( clear ) {
        gl.bindFramebuffer( gl.FRAMEBUFFER, this );
        if ( clear ) {
            gl.viewport( 0, 0, this.width, this.height );
            gl.clearColor( 0.0, 0.0, 0.0, 1.0 );
            gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
        }
    };

    fb.Release = function( clear ) {
        gl.bindFramebuffer( gl.FRAMEBUFFER, null );
        if ( clear ) {
            gl.clearColor( 0.0, 0.0, 0.0, 1.0 );
            gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
        }
    };

    fb.BindTexture = function( textureUnit ) {
        gl.activeTexture( gl.TEXTURE0 + textureUnit );
        gl.bindTexture( gl.TEXTURE_2D, this.color0_texture );
    };

    return fb;
}

initScene();

})();  

</script>

</body>